import React, { Component } from 'react'
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom'
import { connect } from 'react-redux'
import { Input } from 'antd';

import {debounce} from "lodash";

const ERROR_CITY_CODE_MAP = {
    '1558': '0558'
}

const NO_CITY_CODE_MAP = {
    "济源市": '0391',
    "仙桃市": '0728',
    "潜江市": '0728',
    "天门市": '0728',
    "神农架林区": '0719',
    "五指山市": '0898',
    "文昌市": '0898',
    "琼海市": '0898',
    "万宁市": '0898',
    "东方市": '0898',
    "定安县": '0898',
    "屯昌县": '0898',
    "澄迈县": '0898',
    "临高县": '0898',
    "琼中黎族苗族自治县": '0898',
    "保亭黎族苗族自治县": '0898',
    "白沙黎族自治县": '0898',
    "昌江黎族自治县": '0898',
    "乐东黎族自治县": '0898',
    "陵水黎族自治县": '0898',
    "石河子市": '0993',
    "阿拉尔市": '0997',
    "图木舒克市": '0998',
    "五家渠市": '0994',
    "北屯市": '0906',
    "铁门关市": '0996',
    "双河市": '0909',
    "可克达拉市": '0999',
    "昆玉市": '0903'
}

class MapSelector extends Component {
    constructor (props) {
        super(props)
        this.map = null
        this.marker = null
        this.searchService = null

        this.changePositionCallback = []
        this.searchAddressDebounce = debounce(this.searchAddress, 1000)
    }

    componentDidMount () {
        this.initMap()
        const { latitude, longitude } = this.props.value
        this.handleChangePosition({ latitude, longitude })
    }

    componentDidUpdate(preProps) {
        if ('value' in preProps) {
            const { address: preAddress, latitude: preLatitude, longitude: preLongitude, regionCode: preRegionCode, cityCode: preCityCode } = preProps.value;
            const { address, latitude, longitude, regionCode, cityCode } = this.props.value
            if (address !== preAddress ||
                latitude !== preLatitude ||
                longitude !== preLongitude ||
                regionCode !== preRegionCode ||
                cityCode !== preCityCode
            ) {
                this.handleChangePosition({
                    latitude,
                    longitude,
                })
            }
        }
    }

    initMap = () => {
        //获取城市列表接口设置中心点
        this.map = new AMap.Map('mapSelector', {
            resizeEnable: true,
            zoom: 15,
            defaultCursor: 'pointer',
            showIndoorMap: false,
        })
        this.map.on('complete', () => {
            this.changePositionCallback.forEach(callback => {
                typeof callback === "function" && callback()
            })
            AMap.event.addListener(this.map, 'click', event => {
                this.setMarker({
                    lat: event.lnglat.getLat(),
                    lng: event.lnglat.getLng()
                })
            })
        });

        this.searchService = new AMap.Geocoder({});
    }

    handleChangePosition = ({ latitude, longitude }) => {
        if (latitude && longitude) {
            if (this.map) {
                this.map.setCenter([longitude, latitude]);
                this.setMarker({
                    lat: latitude,
                    lng: longitude
                })
            } else {
                this.changePositionCallback.push(() => {
                    this.map.setCenter([longitude, latitude]);
                    this.setMarker({
                        lat: latitude,
                        lng: longitude
                    })
                })
            }
        }

    }

    setMarker = ({ lng, lat, regionCode, cityCode }) => {
        this.removeMarkerListener()
        this.marker = new AMap.Marker({
            position: [lng, lat],
            draggable: true,
            cursor: 'move',
            raiseOnDrag: true
        });
        this.map.add(this.marker)
        this.changeAddress({
            latitude: lat,
            longitude: lng,
            regionCode,
            cityCode,
        })
        this.listener = AMap.event.addListener(this.marker, 'dragend', () => {
            const _pos = this.marker.getPosition()
            this.changeAddress({
                latitude: _pos.getLat(),
                longitude: _pos.getLng()
            })
        });
    }

    removeMarkerListener = () => {
        if (this.marker) {
            this.listener && AMap.event.removeListener(this.listener);
            this.map.remove(this.marker)
            this.marker = null;
        }
    }

    changeAddress = ({ address, latitude, longitude, regionCode, cityCode }) => {
        this.props.onChange({
            address: address === undefined ? this.props.value.address : address,
            latitude: latitude === undefined ? this.props.value.latitude : latitude,
            longitude: longitude === undefined ? this.props.value.longitude : longitude,
            regionCode: regionCode === undefined ? this.props.value.regionCode : regionCode,
            cityCode: cityCode === undefined ? Number(this.props.value.cityCode) : Number(cityCode)
        })
    }

    handleAddressChange = (value) => {
        this.changeAddress({ address: value });
        this.searchAddressDebounce(value)
    }

    handleErrorCityCode = (cityCode, district) => {
        if (cityCode) {
            return ERROR_CITY_CODE_MAP[ cityCode ] || cityCode
        } else if (district) {
            return NO_CITY_CODE_MAP[district] || ''
        }
    }

    handleAddressSearch = (value) => {
        const { address } = this.props.value
        address !== value && this.changeAddress({address: value});
        this.searchAddress(value)
    }

    searchAddress = (value) => {
        const { address } = this.props.value
        this.searchService.getLocation(value || address, (status, result) => {
            if (status === 'error') return;
            const pois = result.geocodes
            if (pois && pois.length) {
                const defaultPoi = pois[0]
                this.map.setCenter(defaultPoi.location);
                this.searchService.getAddress(defaultPoi.location, (status, addRes) => {
                    if (status === 'complete'&& addRes.regeocode) {
                        let addressComponent = addRes.regeocode.addressComponent
                        this.setMarker({
                            lat: defaultPoi.location.getLat(),
                            lng: defaultPoi.location.getLng(),
                            regionCode: this.handleErrorCityCode(addressComponent.citycode, addressComponent.district),
                            cityCode: `156${addressComponent.adcode.slice(-6, -2)}00`
                        })
                    }
                });
            }
        });
    }

    render () {
        const { address } = this.props.value
        return (
            <div className="map-selector-container">
                <div className="map-selector-search">
                    <Input id="place"
                           ref="place"
                           placeholder="请输入地址"
                           value={address}
                           onChange={e => this.handleAddressChange(e.target.value)}
                           onPressEnter={e => this.handleAddressSearch(e.target.value)}
                           onBlur={e => this.handleAddressSearch(e.target.value)}
                    />
                </div>
                <div className="map-selector-remark">地址输全省市区方便自动定位，如果没有自动定位请<span className="blue-content" onClick={() => this.handleAddressSearch()}>点击此处</span></div>
                <div className="map-selector-remark">自动定位地址存在略微偏差，请手动拖动校正。</div>
                <div className="map-selector" id="mapSelector" />
            </div>
        )
    }
}

export default MapSelector